//
//  CAIPluginsManager.m
//  CAIPluginsManager
//
//  Created by simon on 2022/1/13.
//

#import "CAIPluginsManager.h"

///获取插件列表
static NSString *const kPluginList_URL = @"/com.chs.app.mobileserver.plugin.get";

///根据摘要判断是否需要更新
static NSString *const kPluginCheck_URL = @"/com.chs.app.mobileserver.plugin.check";


static NSTimeInterval const pluginTime = 60 * 5;

@interface CAIPluginsManager ()

@property (nonatomic, copy) NSString *module;

@property (nonatomic, copy) void(^success)(id data);

@property (nonatomic, copy) void(^failureBlock)(CHSNetworkMetaModel *meta);

@property (nonatomic, copy) NSString *digest;

@property (nonatomic, copy) NSArray <PluginsModel *>*plugins;

@end


@implementation CAIPluginsManager


- (instancetype)init{
    
    self = [super init];
    if (self) {
        self.isStartPolling = YES;
        self.plugins = [[NSArray alloc] init];
    }
    return self;
}

- (void)getPluginsWithModule:(nullable NSString *)module
                     success:(nullable void(^)(NSArray <PluginsModel *> *plugins))success
                failureBlock:(nullable void(^)(CHSNetworkMetaModel *meta))failureBlock{
    self.module = module;
    if (!module) {
        self.module = @"";
    }
    self.success = success;
    self.failureBlock = failureBlock;
    if (self.isStartPolling) {
        [self requestPolling:@(1)];
    }else{
        [self requestPolling:@(0)];
    }
}


///5分钟间隔
///非轮询的时候，即使没更新情况下也给返回本地缓存数据；轮询的时候，没更新情况下不返回数据;
- (void)requestPolling:(NSNumber *)polling{
    
    NSTimeInterval time =  self.pluginTimeInterval <=0 ? pluginTime :self.pluginTimeInterval;
    if ([polling boolValue] == YES) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(requestPolling:) object:polling];
    }
    __weak __typeof(self)weakSelf = self;
    [CAIPluginsManager requestPluginsCheckUpdateWithModule:self.module digest:self.digest success:^(BOOL update) {
        
        if ([polling boolValue] == YES) {
            [weakSelf performSelector:@selector(requestPolling:) withObject:polling afterDelay:time];
        }
        if (update) {
            [CAIPluginsManager requestPluginsWithModule:self.module success:^(CAIPluginModel * model) {
                
                if (weakSelf.success) {
                    weakSelf.digest = model.digest;
                    weakSelf.plugins = model.plugins;
                    weakSelf.success(weakSelf.plugins);
                }
                
            } failureBlock:^(CHSNetworkMetaModel * _Nonnull meta) {
                if (weakSelf.failureBlock) {
                    weakSelf.failureBlock(meta);
                }
            }];
        }else{
            if (!weakSelf.isStartPolling) {
                if (weakSelf.success) {
                    weakSelf.success(weakSelf.plugins);
                }
            }
        }
        } failureBlock:^(CHSNetworkMetaModel *meta) {
//            NSLog(@"CheckUpdate,currentThread=%@,currentMode=%@",[NSThread currentThread],[NSRunLoop currentRunLoop].currentMode);
            if (weakSelf.failureBlock) {
                weakSelf.failureBlock(meta);
            }
            if ([polling boolValue] == YES) {
                [weakSelf performSelector:@selector(requestPolling:) withObject:polling afterDelay:time];
            }
        }];
}



+ (void)requestPluginsWithModule:(nullable NSString *)module
                     success:(nullable void(^)(CAIPluginModel *model))success
                failureBlock:(nullable void(^)(CHSNetworkMetaModel *meta))failureBlock{
    
    DataEntity *entity = [[DataEntity alloc] init];
    entity.urlString = kPluginList_URL;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (module) {
        [dic setObject:module forKey:@"module"];
    }
    entity.parameters = dic;
    [CHSNetworkManager requestPOSTWithEntity:entity
                               responseModel:[CAIPluginModel class]
                                successBlock:^(CHSNetworkMetaModel * _Nonnull meta) {
        CAIPluginModel *model = meta.data.model;
        if (success) {
            success(model);
        }
    } failureBlock:^(CHSNetworkMetaModel * _Nonnull meta) {
        
        if (failureBlock) {
            failureBlock(meta);
        }
    }];
}

+ (void)requestPluginsCheckUpdateWithModule:(nullable NSString *)module
                                     digest:(NSString *)digest
                                    success:(nullable void(^)(BOOL update))success
                               failureBlock:(nullable void(^)(CHSNetworkMetaModel *meta))failureBlock{
    
    DataEntity *entity = [[DataEntity alloc] init];
    entity.urlString = kPluginCheck_URL;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (module) {
        [dic setObject:module forKey:@"module"];
    }
    if (digest) {
        [dic setObject:digest forKey:@"digest"];
    }
    entity.parameters = dic;
    [CHSNetworkManager requestPOSTWithEntity:entity
                               responseModel:[PluginsCheckUpdateModel class]
                                successBlock:^(CHSNetworkMetaModel * _Nonnull meta) {
        
        PluginsCheckUpdateModel *model = meta.data.model;
        if (success) {
            success(model.update);
        }

    } failureBlock:^(CHSNetworkMetaModel * _Nonnull meta) {
        
        if (failureBlock) {
            failureBlock(meta);
        }
    }];
}

@end
